//
//  GetAddBuyGoodsViewController1.m
//  TryShopping
//
//  Created by panquanReabam.com on 16/10/19.
//  Copyright © 2016年 RuiBen. All rights reserved.
//

#import "GetAddBuyGoodsViewController1.h"

#import "ZJSwitch.h"
#import "MJRefresh.h"
#import "GetAddBuyGoodsCell.h"
#import "GetAddBuyGoodsModel.h"
@interface GetAddBuyGoodsViewController1 ()<UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource>
@end
@implementation GetAddBuyGoodsViewController1
{
    NSMutableArray*title;
    NSMutableArray*couponId ;
    NSMutableArray*price ;
    NSMutableArray*couponIds ;
    NSMutableArray*headerModelArray ;
    NSString* userToken;
    NSString*pid;
      NSString*specId;
       NSString*itemId;
    UITableView*table;
    UIView*noDataView;
   }
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
  
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1]];
    lineLabel.alpha=1;
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    
    
    if ([self.chooseStr isEqualToString:@"领赠品"]||[self.chooseStr isEqualToString:@"重领赠品"]) {
        
       self.title=self.chooseStr;
    }else if ([self.chooseStr isEqualToString:@"去换购"]||[self.chooseStr isEqualToString:@"重新换购"]){
        
       self.title=self.chooseStr;
    }

    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
   
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [noDataView removeFromSuperview];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    [table registerClass:[GetAddBuyGoodsCell class] forCellReuseIdentifier:@"GetAddBuyGoodsViewController"];
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
    headerModelArray=[[NSMutableArray alloc]init];
    pid=@"";
   

    
    
    if (self.items.count>0) {
        
    
       
        if (self.items.count==0) {
            
            noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
            [self.view addSubview:noDataView];
            UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
            noImage.image=[UIImage imageNamed:@"meiyoushuju"];
            [noDataView addSubview:noImage];
            UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
            noLabel.text=@"没有列表数据，赶紧去添加！";
            noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
            noLabel.textAlignment=NSTextAlignmentCenter;
            [noDataView addSubview:noLabel];        }else{
            
            for (NSDictionary* dicc in self.items )
            {
              
                    if ([[NSString stringWithFormat:@"%@",[dicc objectForKey:@"isCurrent"]]isEqualToString:@"Y"]) {
//                        itemId=[NSString stringWithFormat:@"%@",[dicc objectForKey:@"itemId"]];
//                        specId=[NSString stringWithFormat:@"%@",[dicc objectForKey:@"specId"]];
                        pid=[NSString stringWithFormat:@"%@",[dicc objectForKey:@"pid"]];
                    //默认的
                }

                
                GetAddBuyGoodsModel *model=[GetAddBuyGoodsModel mj_objectWithKeyValues:dicc];
                [headerModelArray addObject:model];
                
            }
        }
        [table reloadData];
    
    
    
    }else{
    

    
    
    
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:userToken forKey:@"tokenId"];
        [param setValue:self.shopCartId forKey:@"shopCartId"];
    
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSLog(@"-----%@",param);
        [HttpRequest requestData:@"Business/ShopCart/Gifts" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                NSLog(@"-----%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    
                  
                    if ([self.chooseStr isEqualToString:@"领赠品"]||[self.chooseStr isEqualToString:@"重领赠品"]) {
                        
                        NSMutableArray *mArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"gifts"]];
                        if (mArray.count==0) {
                            
                            noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                            [self.view addSubview:noDataView];
                            UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                            noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                            [noDataView addSubview:noImage];
                            UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                            noLabel.text=@"没有列表数据，赶紧去添加！";
                            noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                            noLabel.textAlignment=NSTextAlignmentCenter;
                            [noDataView addSubview:noLabel];                           }else{

                        for (NSDictionary* dicc in mArray )
                        {
                            
                            if ([[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"isCurrent"]]isEqualToString:@"Y"]&&[[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"isAvailable"]]isEqualToString:@"Y"]) {
                                pid=[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"pid"]];
                            } //默认的
                            
                            GetAddBuyGoodsModel *model=[GetAddBuyGoodsModel mj_objectWithKeyValues:dicc];
                            [headerModelArray addObject:model];
                            
                        }
                        }
                        [table reloadData];
                    }else if ([self.chooseStr isEqualToString:@"去换购"]||[self.chooseStr isEqualToString:@"重新换购"]){
                        
                         NSMutableArray *mArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"exchangeItems"]];
                        if (mArray.count==0) {
                            
                            noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                            [self.view addSubview:noDataView];
                            UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                            noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                            [noDataView addSubview:noImage];
                            UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                            noLabel.text=@"没有列表数据，赶紧去添加！";
                            noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                            noLabel.textAlignment=NSTextAlignmentCenter;
                            [noDataView addSubview:noLabel];                           }else{

                        for (NSDictionary* dicc in mArray )
                        {
                            if ([[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"isCurrent"]]isEqualToString:@"Y"]&&[[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"isAvailable"]]isEqualToString:@"Y"]) {
                                pid=[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"pid"]];
                            } //默认的
                            GetAddBuyGoodsModel *model=[GetAddBuyGoodsModel mj_objectWithKeyValues:dicc];
                            [headerModelArray addObject:model];
                            
                        }}
                        [table reloadData];
                    }
                   
                }else{
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [Global showTextHudSub:requestResultStr view:self.view];
                }}
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }];
    

    }
    
    
    
    UIButton* tureBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, ScreenHeight-45, ScreenWidth, 45)];
    [tureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [tureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    tureBtn.backgroundColor=luseColor;
    CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){204.0/255.0,153.0/255.0, 51.0/255.0, 1.0});
    [tureBtn.layer setBorderColor:tureBTncolorref];//边框颜色
    [tureBtn addTarget:self action:@selector(ture:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tureBtn];
    
}
-(void)ture:(UIButton*)sender{

    
    if ( [[Global getJudgeTheErrorStr:pid]isEqualToString:@""]||pid==NULL) {
        [self showAlertMessage:@"请选择商品！"];
    }else{
        if (self.items.count>0) {
            
            
            [_mDelegate updates:itemId :specId :pid];
             [self.navigationController popViewControllerAnimated:YES];
            
        }else{
        
        
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:userToken forKey:@"tokenId"];
    [param setValue:self.shopCartId forKey:@"shopCartId"];
    [param setValue:pid forKey:@"pid"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    NSLog(@"-----%@",param);
    [HttpRequest requestData:@"Business/ShopCart/AddGift" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"-----%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                [_mDelegate update:@""];
                
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }}
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];

    }
    }

}

#pragma mark - Table view data source
#pragma mark - Table view delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [headerModelArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GetAddBuyGoodsCell*cell = [tableView dequeueReusableCellWithIdentifier:@"GetAddBuyGoodsViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    for (UIView *view in [cell subviews]){
        [view removeFromSuperview];
    }

    cell.GetAddBuyGoodsModel=headerModelArray[indexPath.row];
// cell.mDelegate=self;
    
       return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  114;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
      GetAddBuyGoodsModel *model=headerModelArray[indexPath.row];
        if ([model.isAvailable isEqualToString:@"Y"]) {
        for (int i=0;  i<headerModelArray.count; i++) {
            NSIndexPath *indexPath1 =[NSIndexPath indexPathForRow:i inSection:0 ];
            UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath1];
            GetAddBuyGoodsCell *sharecell=(GetAddBuyGoodsCell *)cell;
             [sharecell.chooseBtn1 setImage:[UIImage imageNamed:@"quans"] forState:UIControlStateNormal];
        }
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        GetAddBuyGoodsCell *sharecell=(GetAddBuyGoodsCell *)cell;
        [sharecell.chooseBtn1 setImage:[UIImage imageNamed:@"gous"] forState:UIControlStateNormal];
        
        pid=model.pid;
        specId=model.specId;

        itemId=model.itemId;
        }else{
        
            [self showAlertMessage:@"不可以领取！"];
        }
    
    
}
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
@end
